package com.hyf.weekindicator.support;

import android.content.Context;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyf.weekindicator.R;

/**
 * Created by Administrator on 2018/6/2.
 */

public class WeekIndicatorView extends FrameLayout {
    private boolean isInit = false;

    private SquareFramLayout indicatorView;
    private LinearLayout itemParentView;

    public interface OnItemClickListener {
        void onItemClick(TextView textView, int position);
    }

    public WeekIndicatorView(@NonNull Context context) {
        super(context);
    }

    public WeekIndicatorView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    private String[] titles;
    private ViewPager viewPager;
    private int selectPosition;
    private OnItemClickListener onItemClickListener;

    public WeekIndicatorView init(String[] titles, int position, OnItemClickListener onItemClickListener) {
        if (isInit) new RuntimeException("you had already init()");
        this.titles = titles;
        if (position >= titles.length || position < 0) {
            selectPosition = 0;
        } else {
            selectPosition = position;
        }
        this.onItemClickListener = onItemClickListener;
        indicatorCount = titles.length;
        isInit = true;
        return this;
    }

    public WeekIndicatorView init(ViewPager viewPager, int position, OnItemClickListener onItemClickListener) {
        if (isInit) new RuntimeException("you had already init()");
        indicatorCount = viewPager.getAdapter().getCount();
        this.viewPager = viewPager;
        if (position >= indicatorCount || position < 0) {
            selectPosition = 0;
        } else {
            selectPosition = position;
        }
        this.viewPager.removeOnPageChangeListener(onPageChangeListener);
        this.viewPager.addOnPageChangeListener(onPageChangeListener);
        this.onItemClickListener = onItemClickListener;
        isInit = true;
        return this;
    }

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            setCurrentItem(position, true);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };

    private int indicatorColor = -999;

    public WeekIndicatorView indicatorColor(int indicatorColor) {
        this.indicatorColor = indicatorColor;
        return this;
    }

    private int textColor = Color.parseColor("#737373");

    public WeekIndicatorView textColor(int textColor) {
        this.textColor = textColor;
        return this;
    }

    private int dip2px(float dpValue) {
        final float scale = getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private int indicatorCount = 0;
    private int indicatorWidth = 0;

    public void build() {
        if (!isInit) return;
        getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
    }


    private void setCurrentItem(final int position, boolean smoothScroll) {
        if (indicatorView == null || itemParentView == null) return;
        int distance = position - selectPosition;

        final TextView beforeTextView = (TextView) ((SquareFramLayout) itemParentView.getChildAt(selectPosition)).getChildAt(0);
        final TextView currentTextView = (TextView) ((SquareFramLayout) itemParentView.getChildAt(position)).getChildAt(0);


//        if (smoothScroll) {
        Animation translateAnimation = createTranslateAnimation(distance, smoothScroll);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                indicatorView.clearAnimation();
                // 位移至指定位置
                int left = indicatorWidth * position;
                int top = 0;
                int right = left + indicatorWidth;
                int bottom = top + indicatorWidth;
                indicatorView.layout(left, top, right, bottom);
                beforeTextView.setTextColor(textColor);
                currentTextView.setTextColor(Color.WHITE);
                selectPosition = position;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        indicatorView.startAnimation(translateAnimation);
//        } else {
//            // 位移至指定位置
//            int left = indicatorWidth * position;
//            int top = 0;
//            int right = left + indicatorWidth;
//            int bottom = top + indicatorWidth;
//            indicatorView.layout(left, top, right, bottom);
//            beforeTextView.setTextColor(textColor);
//            currentTextView.setTextColor(Color.WHITE);
//            selectPosition = position;
//        }

    }

    private Animation createTranslateAnimation(int distance, boolean smoothScroll) {
        TranslateAnimation translateAnimation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF,
                0,
                Animation.RELATIVE_TO_SELF,
                distance * 1.0f,
                Animation.RELATIVE_TO_SELF,
                0,
                Animation.RELATIVE_TO_SELF,
                0
        );
        translateAnimation.setDuration(smoothScroll ? 200 : 0);
        translateAnimation.setFillAfter(true);
        return translateAnimation;
    }

    private ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (indicatorCount == 0) return;
            removeAllViews();
            indicatorWidth = getMeasuredWidth() / indicatorCount;
            Drawable drawable = getResources().getDrawable(R.drawable.shape_bg_cicle);
            if (indicatorColor != -999) {
                drawable.setColorFilter(indicatorColor, PorterDuff.Mode.SRC_IN);
            }
            // 绘制indicator
            {
                indicatorView = new SquareFramLayout(getContext());
                int padding = dip2px(8);
                indicatorView.setPadding(padding, padding, padding, padding);
                TextView textView = new TextView(getContext());
                textView.setBackgroundDrawable(drawable);
                ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(indicatorWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
                indicatorView.setLayoutParams(layoutParams);
                indicatorView.addView(textView);
                addView(indicatorView);
            }

            itemParentView = new LinearLayout(getContext());
            itemParentView.setOrientation(LinearLayout.HORIZONTAL);
            for (int i = 0; i < indicatorCount; i++) {
                final int position = i;

                SquareFramLayout squareFramLayout = new SquareFramLayout(getContext());
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);
                params.weight = 1;
                squareFramLayout.setLayoutParams(params);
                // 每个item的text view
                final TextView textView = new TextView(getContext());
                textView.setGravity(Gravity.CENTER);
                textView.setText(titles == null ? viewPager.getAdapter().getPageTitle(i) : titles[i]);
                textView.setTextColor(textColor);
                squareFramLayout.addView(textView);
                squareFramLayout.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (onItemClickListener != null) {
                            onItemClickListener.onItemClick(textView, position);
                        }
                        setCurrentItem(position, true);
                        if (viewPager != null) viewPager.setCurrentItem(position, true);
                    }
                });
                itemParentView.addView(squareFramLayout);
            }
            addView(itemParentView);

            setCurrentItem(selectPosition, true);
            if (viewPager != null) viewPager.setCurrentItem(selectPosition);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
            }
        }
    };
}
